package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.RegisterReq;
import com.ydkj.a37e_mall.Classes.Model.Request.VerificateCodeReq;
import com.ydkj.a37e_mall.Classes.Model.Response.RegisterResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/1/9.
 * <p>
 * 快速注册
 */


public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private Activity mActivity;
    private EditText et_phone_number, et_verificate_code, et_password1, et_password2, et_recommendation_code;
    private TextView tv_send_verificate_code;
    private TextView tv_verificate_message, tv_complete;
    private ImageView img_back, scan_img;
    private LinearLayout lly_protocol;
    private String secret;
    private MyApplication myApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        mActivity = this;
//        initWindow();
        init();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        myApplication = MyApplication.getInstance();
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        scan_img = (ImageView) mActivity.findViewById(R.id.scan_img);
        tv_send_verificate_code = (TextView) mActivity.findViewById(R.id.tv_send_verificate_code);
        tv_verificate_message = (TextView) mActivity.findViewById(R.id.tv_verificate_message);
        tv_complete = (TextView) mActivity.findViewById(R.id.tv_complete);
        et_phone_number = (EditText) mActivity.findViewById(R.id.et_phone_number);
        et_verificate_code = (EditText) mActivity.findViewById(R.id.et_verificate_code);
        et_password1 = (EditText) mActivity.findViewById(R.id.et_password1);
        et_password2 = (EditText) mActivity.findViewById(R.id.et_password2);
        et_recommendation_code = (EditText) mActivity.findViewById(R.id.et_recommendation_code);
        lly_protocol = (LinearLayout) mActivity.findViewById(R.id.lly_protocol);


        tv_complete.setOnClickListener(this);
        tv_send_verificate_code.setOnClickListener(this);
        img_back.setOnClickListener(this);
        lly_protocol.setOnClickListener(this);
        scan_img.setOnClickListener(this);
    }

    CountDownTimer countDownTimer = new CountDownTimer(120000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tv_send_verificate_code.setText(millisUntilFinished / 1000 + "秒");
            tv_send_verificate_code.setBackgroundResource(R.drawable.right_angle_rectangle_bg_gray);
            tv_send_verificate_code.setTextColor(getResources().getColor(R.color.side_text));
        }

        @Override
        public void onFinish() {
            tv_send_verificate_code.setText("发送验证码");
            tv_send_verificate_code.setBackgroundResource(R.drawable.right_angle_rectangle_red_all);
            tv_send_verificate_code.setTextColor(getResources().getColor(R.color.ffffff));
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_complete://完成
//                post();
                if (et_verificate_code.getText().toString().equals("")) {
                    CommonUtil.showToast(mActivity, "请输入验证码");
                    return;
                }
                if (et_phone_number.getText().toString().equals("")) {
                    CommonUtil.showToast(mActivity, "请输入手机号码");
                    return;
                }
                if (et_password1.getText().toString().equals(et_password2.getText().toString())) {
                    Complete();
                } else {
                    CommonUtil.showToast(mActivity, "您的密码输入不一致");
                }

                break;
            case R.id.tv_send_verificate_code://发送验证码
                if (et_phone_number.getText().toString().equals("")) {
                    CommonUtil.showToast(mActivity, "请输入手机号码");
                    return;
                }
                if (tv_send_verificate_code.getText().toString().equals("发送验证码")) {
                    VerificateCode(et_phone_number.getText().toString());
                    countDownTimer.start();
                    tv_verificate_message.setVisibility(View.VISIBLE);
                } else {
                    return;
                }
                break;
            case R.id.lly_protocol://查看协议
//                Intent intent = new Intent(mActivity, Procotol.class);
//                intent.putExtra("name", "用户协议");
//                intent.putExtra("category", "1");
//                startActivity(intent);
                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.scan_img:
                Intent intent = new Intent();
                intent.setClass(mActivity, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, 1);
                break;

        }
    }


    public void post() {
        Log.e("ssss", "11111");
        String url = "http://192.168.31.188:8083/api/member/user_info/1";
        RequestParams params = new RequestParams();

        Log.e("ssss", "22222");
//        params.add(HTTP.CONTENT_TYPE,
//                "application/x-www-form-urlencoded;charset=UTF-8");
        params.put("secret", "123123");
        Log.e("ssss", "33333");
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

        asyncHttpClient.put(url, params, new JsonHttpResponseHandler() {

            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("ssss", "44444");
                Log.e("ssss", "responseString==>" + response.toString());
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("ssss", "555555");
                Log.e("ssss", "responseString==>" + responseString);
                Log.e("ssss", "statusCode==>" + statusCode);

            }
        });

//        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                Log.e("ssss", "444444");
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                Log.e("ssss", "555555");
//            }
//        });


    }


    //获取短信验证码
    public void VerificateCode(String mobile) {
        Log.e("ssss", "mobile==>" + mobile);

        CustomProgressDialog.createDialog(mActivity).show();
        VerificateCodeReq req = new VerificateCodeReq();
        req.setMobile(mobile);
        req.setType("register");

        try {
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(req.getSecret());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("ssss", "secret==>" + secret);
        String url = Const.COMMON_ADDRESS + req.urlString();
        Log.e("ssss", "url==>" + url);

        params.put("secret", secret);
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("ssss", "短信验证码==》" + response);
                Log.e("ssss", "statusCode==>" + statusCode);
                Log.e("ssss", "111111==>");
                if (errno.equals("000")) {
//                    VerificateCodeResp resp = GsonImpl.get().toObject(response.toString(), VerificateCodeResp.class);
                    CommonUtil.showToast(mActivity, errmsg);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("ssss", "22222==>");
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }


    //完成
    public void Complete() {
        CustomProgressDialog.createDialog(mActivity).Show();
        RegisterReq req = new RegisterReq();
        req.setMobile(et_phone_number.getText().toString());
        req.setPassword(et_password1.getText().toString());
        req.setVerification(et_verificate_code.getText().toString());
        req.setInvite(et_recommendation_code.getText().toString());
        req.setAlias(myApplication.getChannelID());
        req.setDevice_type("3");
        String url = Const.COMMON_ADDRESS + req.urlString();
        try {
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(req.getSecret());
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Log.e("ssss", "Mobile==>" + et_phone_number.getText().toString());
        Log.e("ssss", "Password==>" + et_password1.getText().toString());
        Log.e("ssss", "Verification==>" + et_verificate_code.getText().toString());
        Log.e("ssss", "Invite==>" + et_recommendation_code.getText().toString());
        Log.e("ssss", "Alias==>" + myApplication.getChannelID());


        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    RegisterResp resp = GsonImpl.get().toObject(response.toString(), RegisterResp.class);
                    CommonUtil.showToast(mActivity, errmsg);
                    finish();
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    et_recommendation_code.setText(bundle.getString("result"));
                    Log.e("ssss", "二维码URL==》" + bundle.getString("result"));
//                    mTextView.setText(bundle.getString("result"));
//                    //显示
//                    mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                }
                break;
        }
    }
}
